<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {

    protected function _initialize(){

        if(!C('debug'))
        {
            if(! session("?wxuser"))
            {
                $this->redirect("Wechat/wxoauth",['rnd'=>time()]);
            }
        }

    }


    public function index()
    {

        $openid=session('openid');
        $map=['openid'=>$openid];
        $ans=M('answer')->where($map)->count();
        if($ans)
        {
            $this->assign("message","你已经参与过调查了,感谢您的支持!");
            return $this->display("pub");

        }

        $timu = C("timu");
        $this->assign("timu", $timu);
        $this->display("index");
        // $this->display("test");

        /*  $str='';
          foreach($timu as $key=>$value)
          {
              $str.=danxuan($value);
          }
          echo $str;*/




        // echo genhtml("-----------");
        /*  dump(C('Wechat'));
          echo date("Y/m/d H:i:s");
          $list=M('diaocha')->select();
          dump($list);*/

    }

    public function end()
    {
        $this->display("end");
    }

    public function test()
    {
        echo date("Y/m/d H:i:s");
        dump( C('Wechat.CERTS.CERT'));
        //  $this->display("index");
        //dump(I('session.'));
    }

    public function clear()
    {
        session(null);
    }


    public function save()
    {

        $openid=session('openid');
        $debug=C('debug');
        if($debug)
        {
            $openid='debug';
        }

        $map=['openid'=>$openid];
        $info=M("answer")->where($map)->find();
        if($info)
        {
            if(!$debug)
            {
                die(json_encode(['code'=>400,'message'=>'你已经投过票了,感谢您的参与']));
            }

        }


        //dump(I('post.submitdata'));
        $answer=I('post.submitdata','');
        if(empty($answer)){
            die(json_encode(['code'=>400,'message'=>'网络出现错误,请检查网络!']));
        }
        //"1$1}2$1}3$1|2|5}4$1}5$2}6$1|2|3|4|6|7}7$1|2|3|4|5|6|7}8$1|3|5}9$1}10$1}11$2}12$1"
        $sum_info=[
        ];
        $ar1=explode("}",$answer);
        $ar2=[];
        foreach ($ar1 as $val)
        {
            $tp=explode('$',$val);
            if(count($tp)>=2 && !empty($tp[0]))
            {
                $ar2[]=$tp;
            }
        }


        //ar2为全部问题的答案数组,包含单选,多选答案
        foreach ($ar2 as $k=>$val)
        {
            $tid=$val[0];

            if(empty($tid))
            {
                continue;
            }
            $tiinfo=M('summary')->where(['tid'=>$tid])->find();  //当前题目在统计表中是否有统计记录
            //dump($tiinfo);
            $options=explode("|",$val[1]);


            foreach ($options as $oval)
            {
                if (!$tiinfo['id'])
                {
                    $tiinfo["x" . $oval] = 1;
                }
                else
                {
                    $tiinfo["x" . $oval] += 1;   //在原来投票数的基础上加1,代表统计

                }
            }
            //dump($tiinfo);
            if (!$tiinfo['id'])
            {
                $tiinfo['tid'] = $tid;
                M('summary')->add($tiinfo);

            }
            else
            {
                M('summary')->where('id=' . $tiinfo['id'])->save($tiinfo);
                //dump(M('summary')->getLastSql());
            }




        }



        if($ar2)
        {
            $ans_info=['openid'=>$openid,'createtime'=>time(),'answer'=>$answer];
            M("answer")->add($ans_info);
            echo json_encode(['code'=>200,'message'=>'感谢您的参与','url'=>U('end')]);
        }
        else
        {
            die(json_encode(['code'=>400,'message'=>'答案格式有问题!']));
        }

        //保存答题信息





        // $this->display("end");

    }


    public function hongbao()
    {
        $openid=session('openid');
        if(C('debug'))
        {
            $openid='o_oWgs1s0g9pw6N6U6nMG2paomSw';
        }
        $map=['openid'=>$openid];


        $ans=M('answer')->where($map)->find();
        if(!$ans)
        {
            $this->assign("message","您还没有完成问卷,请先完成问卷");
            $this->display('pub');die;
        }

        //$map['sendtime']=['gt',0];
        $red=M("redpack_log")->where($map)->find();
        if($red)
        {
            $this->assign("message","你已经领取过红包了!");
            $this->display('pub');die;
        }


        $uinfo=session('wxuser');
        $nickname=$uinfo['nickname'];
        $avatar=$uinfo['avatar'];
        $money=100;//红包金额

        $logdata=['openid'=>$openid,'money'=>$money,
            'nickname'=>$nickname,
            'avatar'=>$avatar,
            'createtime'=>time(),
            'sendtime'=>0];
        $logid=M('redpack_log')->add($logdata);
        if($logid)
        {
            $sendname='平行网络';
            $wishing='答题有礼';


            $params = array('openid' => $openid,
                'tid' => $logid,
                'send_name' => $sendname,
                'money' => $money,
                'wishing' => $wishing,
                'act_name' => '奖励红包',
                'remark' => '快来参与!');
            $this->sendredpack($params);

            M('redpack_log')->where("id={$logid}")->setField("sendtime",time());//保存红包发送时间
            $this->assign("message","请去公众号查看红包!");
            return $this->fetch("pub");
        }
        else
        {
            die("保存记录失败!请检查数据库连接是否正常");
        }

    }





    private function sendredpack($params )
    {

        $package = array();
        $package['wxappid'] =C('Wechat.APPID');
        $package['mch_id'] = C('Wechat.MCHID');
        $package['mch_billno'] = $params['tid'];
        $package['send_name'] = $params['send_name'];
        $package['nonce_str'] = random(32);
        $package['re_openid'] = $params['openid'];
        $package['total_amount'] = $params['money'] * 100;
        $package['total_num'] = 1;
        $package['wishing'] = isset($params['wishing']) ? $params['wishing'] : '恭喜发财,大吉大利';
        $package['client_ip'] = '115.29.35.209';
        $package['act_name'] = $params['act_name'];
        $package['remark'] = isset($params['remark']) ? $params['remark'] : '暂无备注';

        $package["total_amount"]= 100;//付款金额，单位分
        $package["min_value"]= 100;//付款金额，单位分
        $package["max_value"]= 100;//付款金额，单位分


        // $package['scene_id'] = isset($params['scene_id']) ? $params['scene_id'] : 'PRODUCT_1';
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
        ksort($package, SORT_STRING);
        $string1 = '';

        foreach ($package as $k => $v) {
            $string1 .= $k . '=' . $v . '&';
        }

        $string1 .= 'key=' .C('Wechat.APIKEY') ;
        $package['sign'] = strtoupper(md5($string1));
        $xml = array2xml($package);
        $extras = array();

        if (is_array(C('Wechat.CERTS'))) {

            $certs=C('Wechat.CERTS');

            $extras['CURLOPT_SSLCERT'] = $certs['CERT'];
            $extras['CURLOPT_SSLKEY'] = $certs['KEY'];
            $extras['CURLOPT_CAINFO'] = $certs['ROOT'];
        }
        else
        {
            die(json_encode("请配置完整的微信支付证书"));
        }

        $resp = ihttp_request($url, $xml, $extras);
        /*   @unlink($certfile);
        @unlink($keyfile);
        @unlink($rootfile);*/

        if (empty($resp['content'])) {
            die( '网络错误');
        }

        $arr = json_decode(json_encode(simplexml_load_string($resp['content'], 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if (($arr['return_code'] == 'SUCCESS') && ($arr['result_code'] == 'SUCCESS')) {
            return true;
        }

        if ($arr['return_msg'] == $arr['err_code_des']) {
            $error = $arr['return_msg'];
        }
        else {
            $error = $arr['return_msg'] . ' | ' . $arr['err_code_des'];
        }

        return die( $error);
    }


}